#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <strings.h>
#include <cstring>  //strerror
#include <cerrno> //errno
#include <unistd.h>
#include <functional>
#include "Log.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"

using func_t = std::function<std::string(std::string)>;
static const int default_sockfd = -1;
std::string default_ip = "127.0.0.1";
uint16_t default_port = 8080;
using namespace LogModule;
class Server
{

public:
    Server(func_t func,uint16_t port = default_port)
        : _sockfd(default_sockfd),
          _inet_addr(port),
          _is_running(false),
          _func(func)
    {
        // 1.创建socket套接字
        // 返回值是文件描述符
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            std::cerr << strerror(errno);
            Die(SOCKETERR);
        }
        LOG(LogLevel::INFO) << "socket success sockfd:" << _sockfd;
        bind(_sockfd,_inet_addr.Addr(),_inet_addr.In_Size());
        LOG(LogLevel::INFO) << "bind success ip:" << _inet_addr.Ip() << " port:" << _inet_addr.Port();
        // 2.填充网络信息并绑定
        // struct sockaddr_in local;
        // 清零
        // bzero(&_local, sizeof(struct sockaddr_in));
        // _local.sin_family = AF_INET;
        // _local.sin_port = htons(_port);
        // // local.sin_addr这是一个结构体，结构体只能整体初始化，不能整体赋值
        // //_local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // //任意绑定
        // _local.sin_addr.s_addr = INADDR_ANY;
        

        // 填充网络信息成功，但没有填充进内核


        // 设置进内核
        //int n = bind(_sockfd, CONV(&_local), sizeof(struct sockaddr_in));

        // if (n < 0)
        // {
        //     LOG(LogLevel::FATAL) << "bind error";
        //     std::cerr << strerror(errno);
        //     Die(BINDERR);
        // }
        // LOG(LogLevel::INFO) << "bind success ip:" << _ip << " port:" << std::to_string(_port);
    }
    ~Server()
    {
        if(_sockfd>default_sockfd)
        {
            close(_sockfd);
        }
    }
    void Start()
    {
        _is_running = true;
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t peer_len = sizeof(struct sockaddr_in);
            // flags 为 0（默认）阻塞
            int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&peer), &peer_len);
            if (n >= 0)
            {
                InetAddr cli(peer);
                buffer[n] = 0;
                std::string word = buffer;
                //char peer_ip[64];
                //inet_ntop(AF_INET,&peer.sin_addr.s_addr,peer_ip,sizeof(peer_ip));
                //uint16_t peer_port = ntohs(peer.sin_port);
                std::string trans = _func(word);//翻译
                LOG(LogLevel::INFO) << "-" <<cli.Ip()<<":"<<cli.Port()  <<"#"<< buffer;
                // std::string info = "echo client#";
                // info += buffer;
                sendto(_sockfd, trans.c_str(), trans.size(), 0, CONV(&peer), peer_len);
            }
            else
            {
                std::cout<<"server error:";
                std::cerr<<strerror(errno);
                Die(SEV_RECV_ERR);
            }
        }
    }

private:
    InetAddr _inet_addr;
    //struct sockaddr_in _local;
    int _sockfd;
    //std::string _ip;
    //uint16_t _port;
    bool _is_running;
    func_t _func;//翻译
};